package com.ljpz.web.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ljpz.common.httpclient.HttpResult;
import com.ljpz.common.service.ApiService;
import com.ljpz.sso.query.bean.User;
import com.ljpz.web.bean.Userinfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 *
 * Created by liujunchen on 2017/2/8.
 */
@Service
public class UserinfoService {
    @Value("${LJPZ_USERINFO_URL}")
    private  String LJPZ_USERINFO_URL  ;
    @Autowired
    private ApiService apiservice  ;
    //解析返回json字符串工具
    private  static  final ObjectMapper MAPPER = new ObjectMapper()  ;
    /**
     * 查询用户中心
     *
     * @param id   用户
     * @return
     */
    public Userinfo queryUserinfo(Long id) {
        //查询用户中心对应的用户信息
        String  url  = LJPZ_USERINFO_URL  + "/userinfo/query/"+id ;
        try {
                String jsonData = this.apiservice.doGet(url);
                if (StringUtils.isNotEmpty(jsonData)) {
                    //如果信息返回
                    return MAPPER.readValue(jsonData, Userinfo.class);
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
            return null;
    }

    /**
     * 更新对应用户信息
     *
     * 如果没有的话就在用户中心自动新建一条记录
     *
     *
     * @param userinfo
     * @return
     */
    public  Boolean  mergeUserinfo(Userinfo  userinfo ){
        Boolean  mergeResult = false ;
        Userinfo   userqueryInfo =  queryUserinfo(userinfo.getUserId());
        String url=null ;
        if (userqueryInfo!=null){
            //发出更新记录的请求
            url=LJPZ_USERINFO_URL+"/userinfo/update" ;
            return  this.handleUserinfo(url, userinfo)  ;
        } else {
            //发出添加记录的请求
            url=LJPZ_USERINFO_URL+"/userinfo/create";
            return   this.handleUserinfo(url,userinfo) ;
        }

    }
    public  Boolean   handleUserinfo(String url ,Object object ){
        try {
            HttpResult httpresult = this.apiservice.doPostJson(url,MAPPER.writeValueAsString(object));
            if (httpresult.getCode().intValue()==200){
                String body = httpresult.getBody();
                JsonNode jsonNode= MAPPER.readTree(body);
                if (jsonNode.get("status").asInt()==200){
                    //请求成功
                    return  true ;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  false  ;
    }
}
